<template>
  <view class="profile-container">
    <view class="profile-header">
      <view class="avatar-container" @click="changeAvatar">
        <image 
          :src="userInfo.imgSrc || defaultAvatar" 
          class="avatar"
          @click="chooseAndUploadAvatar"
        ></image>
        <view class="avatar-edit-icon">
          <text class="iconfont icon-edit"></text>
        </view>
      </view>
      <view class="user-info">
        <text class="username">姓名：{{ userInfo.courierName || '未设置姓名' }}</text>
        <text class="account">账号：{{ userInfo.courierAccount || '未知' }}</text>
        <text class="warehouse">所属仓库：{{ userInfo.warehouseName || '暂未绑定仓库' }}</text>
      </view>
    </view>

    <view class="profile-menu">
      <view 
        class="menu-item" 
        @click="navigateTo('/pages/profile/changePassword')"
      >
        <text class="iconfont icon-lock"></text>
        <text class="menu-text">修改密码</text>
        <text class="iconfont icon-right"></text>
      </view>
      <view class="menu-item" @click="logout">
        <text class="iconfont icon-logout"></text>
        <text class="menu-text">退出登录</text>
        <text class="iconfont icon-right"></text>
      </view>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request'

export default {
  data() {
    return {
      userInfo: {
        id: '',
        courierName: '',
        courierAccount: '',
        phone: '',
        warehouseId: '',
        warehouseName: '',
        roleId: '',
        imgSrc: ''
      },
      defaultAvatar: '/static/default-avatar.png'
    }
  },
  onShow() {
    console.log('courierProfile onShow 被调用');
    this.fetchUserInfo()
  },
  methods: {
    async fetchUserInfo() {
      console.log('fetchUserInfo 方法开始执行');
      console.log('本地存储的 courierAccount:', uni.getStorageSync('courierAccount'));
      console.log('本地存储的 courierUserInfo:', uni.getStorageSync('courierUserInfo'));

      // 如果本地存储没有，则从服务器获取
      const courierAccount = uni.getStorageSync('courierAccount')

      try {
        console.log('准备发起获取用户信息的请求');
        const res = await request({
          url: '/courier/profile',
          method: 'GET',
          data: {
            courierAccount: courierAccount
          }
        })

        console.log('获取用户信息的响应:', JSON.stringify(res));

        if (res.code === 200) {
          // 更新用户信息
          this.userInfo = {
            id: res.data.id,
            courierName: res.data.courierName,
            courierAccount: res.data.courierAccount,
            phone: res.data.phone,
            warehouseId: res.data.warehouseId,
            warehouseName: res.data.warehouseName,
            roleId: res.data.roleId,
            imgSrc: res.data.imgSrc
          }

          // 存储到本地
          uni.setStorageSync('courierUserInfo', this.userInfo)
          
          console.log('成功更新用户信息:', this.userInfo);
        } else {
          // 获取用户信息失败
          console.error('获取用户信息失败:', res.message);
          uni.showToast({
            title: res.message || '获取用户信息失败',
            icon: 'none'
          })
        }
      } catch (err) {
        console.error('获取用户信息异常:', err)
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      }
    },
    chooseAndUploadAvatar() {
                uni.chooseImage({ // 选择图片
                    count: 1,
                    success: (res) => { // 图片选择成功的回调（必传），会返回一个对象
                        uni.uploadFile({
                            url: 'http://127.0.0.1:8081/courier/imgLoad', // 注意要写全路径
                            header: {
                                'Content-Type': 'application/json',
                                // 可添加token等认证信息
                                'Authorization': uni.getStorageSync('courierJWT')

                            },
                            filePath: res.tempFilePaths[0],
                            name: 'file', // 这里的name要和后端参数名一致
                            success: (uploadFileRes) => {
                                // 这里uploadFileRes.data就是后端返回的数据
                                uni.showToast({
                                    title: '上传成功',
                                    icon: 'success'
                                })
                            }
                        })
                    }
                })
            },
    // changeAvatar() {
    //   uni.chooseImage({
    //     count: 1,
    //     sourceType: ['album', 'camera'],
    //     success: async (chooseImageRes) => {
    //       const tempFilePaths = chooseImageRes.tempFilePaths
          
    //       // 上传头像
    //       try {
    //         const uploadRes = await this.uploadAvatar(tempFilePaths[0])
            
    //         if (uploadRes.code === 200) {
    //           this.userInfo.imgSrc = uploadRes.data.imgSrc
    //           uni.showToast({
    //             title: '头像上传成功',
    //             icon: 'success'
    //           })
    //         }
    //       } catch (err) {
    //         console.error('头像上传失败:', err)
    //         uni.showToast({
    //           title: '头像上传失败',
    //           icon: 'none'
    //         })
    //       }
    //     }
    //   })
    // },
    // async uploadAvatar(filePath) {
    //   return new Promise((resolve, reject) => {
    //     uni.uploadFile({
    //       url: '/courier/uploadAvatar',
    //       filePath: filePath,
    //       name: 'avatar',
    //       success: (uploadFileRes) => {
    //         const data = JSON.parse(uploadFileRes.data)
    //         resolve(data)
    //       },
    //       fail: (err) => {
    //         reject(err)
    //       }
    //     })
    //   })
    // },
    navigateTo(url) {
      uni.navigateTo({ url })
    },
    logout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 清除本地存储
            uni.removeStorageSync('courierAccount')
            uni.removeStorageSync('courierJWT')

            // 直接跳转到登录页
            uni.reLaunch({
              url: '/pages/login/courierLogin'
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.profile-container {
  background-color: #f4f4f4;
  min-height: 100vh;
}

.profile-header {
  background-color: #007aff;
  color: white;
  padding: 40px 20px 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-container {
  position: relative;
  width: 100px;
  height: 100px;
  margin-bottom: 15px;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  border: 3px solid white;
}

.avatar-edit-icon {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: rgba(0,0,0,0.3);
  border-radius: 50%;
  width: 25px;
  height: 25px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.username, .account, .warehouse {
  margin-bottom: 5px;
  font-size: 16px;
}

.profile-menu {
  background-color: white;
  margin-top: 10px;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.menu-item:last-child {
  border-bottom: none;
}

.iconfont {
  font-size: 20px;
  margin-right: 15px;
  color: #007aff;
}

.menu-text {
  flex-grow: 1;
  color: #333;
}

.icon-right {
  color: #999;
}

.icon-logout {
  color: #ff3b30;
}
</style> 